/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.model.clazz.id;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.beanutils.PropertyUtils;

import com.koylu.caffein.exception.ClazzConfigException;
import com.koylu.caffein.javassist.BeanGenerator;
import com.koylu.caffein.model.caffein.CaffeinConfig;
import com.koylu.caffein.model.clazz.Clazz;
import com.koylu.caffein.model.clazz.ColumnField;
import com.koylu.caffein.model.clazz.Field;
import com.koylu.caffein.model.clazz.ForeignKey;
import com.koylu.caffein.model.clazz.ManyToOne;
import com.koylu.caffein.model.clazz.Node;
import com.koylu.caffein.model.clazz.Property;
import com.koylu.caffein.model.clazz.Relation;
import com.koylu.caffein.model.clazz.validation.ValidateFor;
import com.koylu.caffein.model.clazz.validation.Validation;

public class CompositeId implements Id {

	private String name;
	private String type;
	private Node parent;
	private Class<?> realClass;
	private Class<?> virtualClass;
	private Map<String, Field> fieldMap;
	private List<Validation> validations;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public String getType() {
		return type;
	}
	
	public void setType(String type) {
		this.type = type;
	}

	public Node getParent() {
		return parent;
	}

	public void setParent(Node parent) {
		this.parent = parent;
	}

	public void addChild(Node child) throws Exception{
		if(child instanceof Property){
			((Property)child).setColumnNullable(false);
		}else if(child instanceof ManyToOne && !(child instanceof ForeignId)){
			for(ForeignKey foreignKey:((ManyToOne)child).getChildren()){
				foreignKey.setColumnNullable(false);
			}
		}else{
			throw new ClazzConfigException("invalid child type:"+child.getClass().getName(), this);
		}
		if (fieldMap == null) {
			fieldMap = new TreeMap<String, Field>();
		}
		Field field = (Field) child;
		fieldMap.put(field.getName(), field);
		child.setParent(this);
	}

	public Collection<Field> getChildren() {
		return fieldMap.values();
	}
	
	public Field getChild(String name) {
		return fieldMap.get(name);
	}
	
	public Object toObject(CaffeinConfig caffeinConfig, Object object, ResultSet resultSet) throws Exception {
		Object id = getRealClass(caffeinConfig).newInstance();
		for (Field field : getChildren()) {
			PropertyUtils.setProperty(id, field.getName(), field.toObject(caffeinConfig, object, resultSet));
		}
		return id;
	}
	
	public Object toEmptyObject(CaffeinConfig caffeinConfig, Clazz clazz) throws Exception {
		Object id = getRealClass(caffeinConfig).newInstance();
		for (Field field : getChildren()) {
			Object value = field.toEmptyObject(caffeinConfig, clazz);
			if(value != null){
				PropertyUtils.setSimpleProperty(id, field.getName(), value);	
			}
		}
		return id;
	}
	
	public Object copy(CaffeinConfig caffeinConfig, Object object) throws Exception {
		Object id = getRealClass(caffeinConfig).newInstance();
		for (Field field : getChildren()) {
			PropertyUtils.setProperty(id, field.getName(), field.copy(caffeinConfig, PropertyUtils.getProperty(object, field.getName())));
		}
		return id;
	}
	
	public Class<?> getRealClass(CaffeinConfig caffeinConfig) throws Exception{
		if(realClass == null){
			realClass = toVirtualClass(caffeinConfig);
		}
		return realClass;
	}
	
	public Class<?> toVirtualClass(CaffeinConfig caffeinConfig) throws Exception {
		if(virtualClass == null){
			if( type == null || "".equals(type)  ){
				BeanGenerator beanGenerator = new BeanGenerator(name);
				for (Field field : getChildren()) {
					beanGenerator.addProperty(field.getName(), field.toVirtualClass(caffeinConfig));
				}
				virtualClass = beanGenerator.createClass();
			}else{
				try {
					virtualClass = Class.forName(type);	
				} catch (Exception e) {
					throw new ClazzConfigException("class not found:"+type, e, this);
				}				
			}
		}
		return virtualClass;
	}

	public String toUniqueId(CaffeinConfig caffeinConfig, Object id) throws Exception {
		StringBuffer uniqueId = new StringBuffer();
		for (Iterator<Field> iterator = fieldMap.values().iterator(); iterator.hasNext();) {
			Field field = iterator.next();
			if (field.getChildren() == null) {//Property
				uniqueId.append(((ColumnField) field).getConverter(caffeinConfig).objectToString(PropertyUtils.getProperty(id, field.getName())));
			} else {//ManyToOne
				Object value = PropertyUtils.getProperty(id, field.getName());
				Clazz foreignClazz = ((Relation)field).getForeignClazz(caffeinConfig);
				uniqueId.append(foreignClazz.getId().toUniqueId(caffeinConfig, PropertyUtils.getProperty(value, foreignClazz.getId().getName())));
			}
			if (iterator.hasNext()) {
				uniqueId.append("-");
			}
		}
		return uniqueId.toString();
	}
	
	public String[] getGeneratedColumnNames() {
		return null;
	}
	
	public void setGeneratedKeys(CaffeinConfig caffeinConfig, Object object, PreparedStatement preparedStatement) throws Exception {}

	public List<Validation> getValidations() {
		return validations;
	}

	public void setValidations(List<Validation> validations) {
		this.validations = validations;
	}
	
	public void validate(CaffeinConfig caffeinConfig, Clazz clazz, Object object, ValidateFor validateFor) throws Exception {
		if (validations != null) {
			for (Validation validation : validations) {
				validation.validate(caffeinConfig, clazz, this, object, validateFor);
			}
		}
        for (Field field : getChildren()) {
            field.validate(caffeinConfig, clazz, object, validateFor);
        }
	}
	
	public String getPath(CaffeinConfig caffeinConfig) throws Exception {
		return name;
	}

	public String toString() {
		return getClass().getName()+"["+name+"]";
	}
}